import csv
import requests
import json


class WeatherService:
    def __init__(self, amap_keys_file):
        self.amap_keys = self.load_amap_keys(amap_keys_file)
        self.current_key_index = 0

    @staticmethod
    def load_amap_keys(amap_keys_file):
        keys = []
        with open(amap_keys_file, 'r', newline='') as file:
            reader = csv.reader(file)
            header = next(reader, None)  # 获取 CSV 文件的头部（第一行）

            if header and 'key' in header:
                key_index = header.index('key')
                for row in reader:
                    if len(row) > key_index:
                        keys.append(row[key_index])

        return keys

    def switch_amap_key(self):
        self.current_key_index = (self.current_key_index + 1) % len(self.amap_keys)

    def get_weather_details(self, city):
        for key in self.amap_keys:
            url = (f'https://restapi.amap.com/v3/weather/weatherInfo?key={key}'
                   f'&city={city}&output=json&extensions=all')

            try:
                response = requests.get(url)
                data = json.loads(response.text)

                # 检查是否有有效的天气数据
                if 'lives' in data and len(data['lives']) > 0:
                    weather_info = data['lives'][0]
                    return {
                        'province': weather_info['province'],
                        'city': weather_info['city'],
                        'temperature': weather_info['temperature'],
                        'weather': weather_info['weather'],
                        'wind_direction': weather_info['winddirection'],
                        'wind_power': weather_info['windpower'],
                        'humidity': weather_info['humidity'],
                        'report_time': weather_info['reporttime']
                    }
                elif 'forecasts' in data and len(data['forecasts']) > 0:
                    forecast_info = data['forecasts'][0]
                    return {
                        'province': forecast_info['province'],
                        'city': forecast_info['city'],
                        'report_time': forecast_info['reporttime'],
                        'casts': forecast_info['casts']
                    }
            except Exception as e:
                print(f"Error fetching weather details for city {city} with key {key}: {e}")
                continue

        return None
